package com.zcsy.manage.web.mall;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.model.RequestConstants;
import com.zcsy.commons.model.RequestJson;
import com.zcsy.commons.unique.UniqueNumberUtils;
import com.zcsy.manage.model.base.CommonConfig;
import com.zcsy.manage.model.mall.IntegralConfig;
import com.zcsy.manage.model.system.Dict;
import com.zcsy.manage.model.system.User;
import com.zcsy.manage.service.base.ICommonConfigService;
import com.zcsy.manage.service.mall.IIntegralConfigService;
import com.zcsy.manage.service.system.IDictService;
import com.zcsy.manage.service.system.IUserService;
import com.zcsy.manage.web.common.LogUtils;

/**
 * @Title: IntegralConfigController.java
 * @Package： com.zcsy.manage.web.mall
 * @Description: 积分配置控制层
 * @author liuying 1075817474@qq.com
 * @Copyright: 2015 武汉中财数元信息技术有限公司 All rights reserved.
 * @date 2016年5月10日
 * @version 1.0
 * @see JDK1.7.0_75
 * @since
 */
@Controller
@RequestMapping(value = "/integralConfig")
public class IntegralConfigController {

	/** 仅积分配置使用 */
	private static final String INTEGRAL_NAME = "mall_integral_config";
	/** 正常 */
	private static final int STATE_SUCCESS = 1;
	/** 禁用 */
	private static final int STAET_FORBIDEN = 0;

	@Autowired
	private IIntegralConfigService integralConfigService;

	@Autowired
	private ICommonConfigService commonConfigService;

	@Autowired
	private IUserService UserService;

	@Autowired
	private IDictService dictService;
	
	/**
	 * @Description 积分配置列表显示<br>
	 * @param pNo
	 *            起始页
	 * @param configLabel
	 *            配置描述
	 * @param req
	 *            用户请求
	 * @return 跳转页面URL
	 * @author liuying 1075817474@qq.com
	 * @date 2016年5月10日
	 * @see
	 */
	@RequestMapping(value = "integralConfigList", method = RequestMethod.GET)
	public String integralConfigList(Model model, Integer pNo, Integer pSize, 
			String configLabel, HttpServletRequest req) {
		if (pNo == null) {
			pNo = Constants.PAGE_NO;
		}

		Integer pageSize;
		if (pSize == null) {
			pageSize = Constants.PAGE_SIZE;
		} else {
			switch (pSize) {
				case 0: pageSize = Constants.PAGE_SIZE;
				break;
				case 1: pageSize = Constants.PAGE_SIZE_TWENTY;
				break;
				case 2: pageSize = Constants.PAGE_SIZE_FIFTY;
				break;
				default:pageSize = Constants.PAGE_SIZE;
				break;
			}
		}
		
		// 此处添加PageHelper将会走拦截器，进行分页，分页方法只针对紧跟着PageHelper的查询方法有效
		PageHelper.startPage(pNo, pageSize);

		IntegralConfig integralConfig = new IntegralConfig();
		CommonConfig commonConfig = new CommonConfig();

		// 名称不为空时，设置名称
		if (StringUtils.isNotEmpty(configLabel)) {
			integralConfig.setLabel(configLabel);
		}

		integralConfig.setState(STAET_FORBIDEN);

		List<IntegralConfig> integralConfigs = integralConfigService
				.selectByKeyword(integralConfig);
		PageInfo<IntegralConfig> info = new PageInfo<IntegralConfig>(
				integralConfigs);

		// 获取每日积分上限
		commonConfig = commonConfigService.getByName(INTEGRAL_NAME);
		try {
		    if(null != commonConfig) {
		        int integralMax = Integer.parseInt(commonConfig.getValue());
		        model.addAttribute("integralMax", integralMax);
		    }

		} catch (NumberFormatException e) {
		}

		model.addAttribute("integralConfig", info);
		model.addAttribute("currentPage", pNo);
		model.addAttribute("pSize", pSize);
		model.addAttribute("configLabel", configLabel);

		List<Dict> pageSizes = dictService.getDictFromCache("pageSize");
		model.addAttribute("pageSizes", pageSizes);

		return "mall/integralconfig/integralConfigList";
	}

	/**
	 * @Description 全部业主积分清零
	 * @param request
	 *            用户请求
	 * @param response
	 *            响应
	 * @return 响应结果
	 * @author liuying 1075817474@qq.com
	 * @date 2016年5月11日
	 * @see
	 */
	@RequestMapping(value = "integralAllClear", method = RequestMethod.POST)
	@ResponseBody
	public RequestJson integralAllClear(HttpServletRequest request,
			HttpServletResponse response) {

		RequestJson result = new RequestJson();
		User user = (User)request.getSession().getAttribute(RequestConstants.USER_SESSION_ID);

		UserService.clearOwnerIntegral();
		LogUtils.insertLog("用户将全部业主积分清零", user.getId(), request);

		return result;
	}

	/**
	 * @Description 编辑积分配置<br>
	 * @param id
	 *            主键id
	 * @return 跳转画面URL
	 * @author liuying 1075817474@qq.com
	 * @date 2016年5月10日
	 * @see
	 */
	@RequestMapping(value = "editIntegralConfig", method = RequestMethod.GET)
	public String editIntegralConfig(Model model, String id) {
		try {
			if (!String.valueOf(Constants.STATE_DISABLED).equals(id)) {
				IntegralConfig integralConfig = integralConfigService
						.selectByPrimaryKey(id);
				model.addAttribute("integralConfig", integralConfig);
			}

		} catch (Exception e) {
		}

		return "mall/integralconfig/integralConfigEdit";
	}

	/**
	 * @Description 保存或更新积分配置<br>
	 * @param configLabel
	 *            配置描述
	 * @param configName
	 *            配置名称
	 * @param value
	 *            配置的值
	 * @param configId
	 *            主键id
	 * @param request
	 *            用户请求
	 * @param response
	 *            响应
	 * @return 请求结果
	 * @author liuying 1075817474@qq.com
	 * @date 2016年5月10日
	 * @see
	 */
	@RequestMapping(value = "saveOrUpdateConfig", method = RequestMethod.POST)
	@ResponseBody
	public RequestJson saveOrUpdateConfig(String configLabel,
			String configName, Integer value, String configId,
			HttpServletRequest request, HttpServletResponse response) {
		RequestJson result = new RequestJson();
		User user = (User) request.getSession().getAttribute(
				RequestConstants.USER_SESSION_ID);
		try {
			IntegralConfig record = new IntegralConfig();
			record.setLabel(configLabel);
			record.setName(configName);
			record.setValue(value);
			record.setUpdateAccount(user.getLoginname());

			if (configId != null && !"".equals(configId)) {
				record.setId(configId);
				record.setUpdateTime(new Date());
				integralConfigService.update(record);
				LogUtils.insertLog("用户编辑积分配置信息", user.getId(), request);

			} else {
				record.setId(UniqueNumberUtils.get18UniqueNumber());
				record.setUpdateTime(new Date());
				integralConfigService.insert(record);
				LogUtils.insertLog("用户新增积分配置信息", user.getId(), request);

			}

		} catch (Exception e) {
			result.setSuccess(false);
		}

		return result;
	}

	/**
	 * @Description 更改配置状态<br>
	 * @param id 主键id
	 * @param state 用户状态
	 * @return 更新结果
	 * @author liuying 1075817474@qq.com
	 * @date 2016年5月10日
	 * @see
	 */
	@RequestMapping(value = "/integralConfigUpdate", method = RequestMethod.POST)
	@ResponseBody
	public RequestJson integralConfigUpdate(Model model, String id, int state, HttpServletRequest request) {
		RequestJson result = new RequestJson();
		User user = (User)request.getSession().getAttribute(RequestConstants.USER_SESSION_ID);

		int temp = 0;
		try {
			IntegralConfig integralConfig = new IntegralConfig();
			integralConfig.setId(id);
			switch (state) {
			case STATE_SUCCESS:
				temp = STAET_FORBIDEN;
				break;
			case STAET_FORBIDEN:
				temp = STATE_SUCCESS;
				break;
			default:
				temp = STATE_SUCCESS;
				break;
			}
			integralConfig.setState(temp);
			integralConfigService.update(integralConfig);
			LogUtils.insertLog("用户更改积分配置状态", user.getId(), request);

		} catch (Exception e) {
			result.setSuccess(false);
		}

		return result;
	}

	/**
	 * @Description 根据多个id删除数据<br>
	 * @param iDs
	 *            多个id
	 * @param req
	 *            用户请求
	 * @return 请求结果
	 * @author liuying 1075817474@qq.com
	 * @date 2016年5月10日
	 * @see
	 */
	@RequestMapping(value = "deleteConfig", method = RequestMethod.POST)
	@ResponseBody
	public RequestJson deleteConfig(String iDs, HttpServletRequest req) {

		RequestJson result = new RequestJson();
		User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);

		try {
			String ids[] = iDs.split("\\,");
			for (int i = 0; i < ids.length; i++) {
				integralConfigService.delete(ids[i]);
			}
			result.setSuccess(true);
			LogUtils.insertLog("用户删除积分配置", user.getId(), req);
		} catch (NumberFormatException e) {
			result.setSuccess(false);
			result.setMsg("操作失败");
		}

		return result;
	}
}
